<?

/* PartyModel model class.
 * This class contains data model implementation code.
 *
 */ 
class PartyModel extends AGModel
{
  // model data
  var $data;

  function __construct($modelName) 
  {
    parent::__construct($modelName);
    // your constructor code goes here
    $this->maxGroup = 5;
  }
  
  function syncWithFB($uid, $force = false)
  {
    if ($force || time() - $this->user->localRecord['u_lastsync'] > 10*60 || time() == $this->user->localRecord['u_lastsync'])
    {
      $this->fbPartyList = $this->user->fb->api_client->fql_query(
        'SELECT uid,name,pic_square,sex FROM user 
        WHERE uid 
        IN (SELECT uid2 FROM friend WHERE uid1 = '.$uid.' 
        LIMIT 250)');  
      foreach($this->fbPartyList as $friend)
      {
        $userDS = DB_GetDataset('users', $friend['uid'], 'u_fb_uid');
        $userDS['u_fb_uid'] = $friend['uid'];
        $userDS['u_fb_sex'] = $friend['sex'];
        $userDS['u_fb_pic_square'] = $friend['pic_square'];
        $userDS['u_fb_name'] = $friend['name'];
        $userDS['u_status'] = getDefault($userDS['u_status'], 'F');
        $userDS['u_type'] = getDefault($userDS['u_type'], 'player');
        $id = DB_UpdateDataset('users', $userDS);
        $this->fbFriends[$id] = $userDS;
      }
      $this->user->localRecord['u_lastsync'] = time();
      DB_UpdateDataset('users', $this->user->localRecord);
    }
  }
  
  function loadParty($uid)
  {
    //$this->syncWithFB($uid);
    $this->party = DB_GetList('SELECT u_key,u_fb_name,u_fb_pic_square FROM '.getTableName('parties').'
      LEFT JOIN '.getTableName('users').' ON (p_member = u_key)
      WHERE p_party="'.$uid.'"');
    return($this->party);
  }
  
  function loadGroup($uid)
  {
    //$this->syncWithFB($uid);
    $this->party = DB_GetList('SELECT u_key,c_key,c_icon,u_fb_pic_square,c_name,c_level,c_stats,p_type,p_key,p_hp,p_hp_max FROM '.getTableName('parties').'
      LEFT JOIN '.getTableName('users').' ON (p_member = u_key)
      LEFT JOIN '.getTableName('characters').' ON ((c_ref_user = p_member AND p_type != "mob") OR (c_key = p_member AND p_type = "mob"))
      WHERE p_party="'.$uid.'" AND p_group="Y"
      ORDER BY c_level DESC
      LIMIT 5');
    foreach($this->party as $pm)
    {
      $stats = TextToStringList($pm['c_stats']);
      $hp_max = getDefault($stats['HP.effective'], $stats['HP']);
      if ($pm['p_hp_max'] == 0)
        $pm['p_hp'] = $hp_max;
      $pm['p_hp_max'] = $hp_max;
      DB_Update('UPDATE '.getTableName('parties').'
        SET p_hp = '.($pm['p_hp']).',p_hp_max = '.($hp_max).'
        WHERE p_key="'.$pm['p_key'].'"');
    }
    return($this->party);
  }
  
  function RemoveFromGroup($id)
  {
    $pds = DB_GetDataset('parties', $id);
    if ($pds['p_party'] == $this->character->charDS['c_ref_user'])
    {
      $pds['p_group'] = 'N';
      DB_UpdateDataset('parties', $pds);
    }
  }
  
  function AddToGroup($id)
  {
    $glist = DB_GetList('SELECT * FROM '.getTableName('parties').' WHERE
      p_party="'.$this->character->charDS['c_ref_user'].'" AND p_group="Y"');
    $pds = DB_GetDataset('parties', $id);
    if ($pds['p_party'] == $this->character->charDS['c_ref_user'] && sizeof($glist) < $this->maxGroup)
    {
      $pds['p_group'] = 'Y';
      DB_UpdateDataset('parties', $pds);
    }
  }
  
  function autoGroup($uid, $max)
  {
    $currentGroup = $this->loadGroup($uid);
    /*DB_Update('UPDATE '.getTableName('parties').' 
      SET p_group="N"
      WHERE p_party="'.$uid.'"
      ');
    DB_Update('UPDATE '.getTableName('parties').' 
      LEFT JOIN '.getTableName('characters').' ON ((c_ref_user = p_member AND p_type != "mob") OR (c_key = p_member AND p_type = "mob"))
      SET p_group="Y"
      WHERE p_party="'.$uid.'"
      ORDER BY c_level DESC
      LIMIT 5
      ');
    return;
    */$ungrouped = DB_GetList('SELECT p_key FROM '.getTableName('parties').'
      LEFT JOIN '.getTableName('characters').' ON (p_member = c_ref_user)
      WHERE p_party="'.$uid.'" AND p_group="N"
      ORDER BY c_level ASC');
    while (sizeof($currentGroup) <= $max && sizeof($ungrouped)>0)
    {
      $ukds = array_pop($ungrouped);
      $pgrp = DB_GetDataset('parties', $ukds['p_key']);
      $pgrp['p_group'] = 'Y';
      DB_UpdateDataset('parties', $pgrp);
    }
  }
  
  function addInvitedPeople($ids, &$byUser)
  {
    foreach($ids as $fb_uid)
    {
      $uds = DB_GetDataset('users', $fb_uid, 'u_fb_uid');
      $partyDS = DB_GetDatasetWQuery('SELECT * FROM '.getTableName('parties').'
        WHERE p_party="'.$byUser->localRecord['u_key'].'" AND p_member="'.$uds['u_key'].'"');
      if (sizeof($partyDS) == 0)
      {
      $fds = DB_GetDataset('users', $fb_uid, 'u_fb_uid');
        $ivds = array(
          'ip_inviter' => $byUser->localRecord['u_key'],
          'ip_invited_fb_uid' => $fb_uid,
          'ip_invited' => $fds['u_key'],
          'ip_invcode' => $_SESSION['last_inv_code'],
          );
        DB_UpdateDataset('invited_people', $ivds);
      }
    }
  }
  
  function clearInvitesFor($user_uid, $partyId)
  {
    DB_Update('DELETE FROM '.getTableName('invited_people').'
      WHERE ip_invited_fb_uid="'.$user_uid.'" AND ip_inviter="'.$partyId.'"');
  }
  
  function _associateParty($user_id, $party_id)
  {
    $existingParty = DB_GetList('SELECT * FROM '.getTableName('parties').'
      WHERE p_party="'.$party_id.'" AND p_member="'.$user_id.'"
      ');
    if (sizeof($existingParty) == 0)
    {
      $p = array(
        'p_party' => $party_id,
        'p_member' => $user_id,
        );
      DB_UpdateDataset('parties', $p);
      return(true);
    }
    else
    {
      logBackendError('party exists', $existingParty);
      return(false);
    }
  }
  
  function getCPOnJoin($user_id, $partyId, $amount = 3)
  {
    // see how many members the user's party has
    $countDS = DB_GetdatasetWQuery('SELECT count(*) FROM '.getTableName('parties').'
      WHERE p_party="'.$user_id.'"');
    if ($countDS['count(*)'] <= 11)
    {
      $userDS = DB_Getdataset('users', $user_id);
      $userDS['u_cheatpoints'] += $amount;
      DB_UpdateDataset('users', $userDS);
      auditLog('party.joinParty.cp(add)', 'party of user '.$user_id.' gained 3 CP from '.$partyId.' on join, has '.($countDS['count(*)']+1).' members');
    }
    else 
      auditLog('party.joinParty.cp(maxedout)', 'party of user '.$user_id.' gained no CP from '.$partyId.' on join, has '.($countDS['count(*)']+1).' members');
  }

  function joinParty(&$userObject, $partyId)
  {
    $user_id = $userObject->localRecord['u_key'];
    $user_fb_uid = $userObject->localRecord['u_fb_uid'];
    // first, let's see if there are invitations?
    $inv = DB_GetList('SELECT * FROM '.getTableName('invited_people').'
      WHERE ip_inviter="'.$partyId.'" AND ip_invited_fb_uid="'.$user_fb_uid.'"
      ');
    if (sizeof($inv)>0)
    {
      // now, the user joins the inviter's party
      if ($this->_associateParty($user_id, $partyId))
      {
        $this->getCPOnJoin($user_id, $partyId);
      }
      $this->clearInvitesFor($user_fb_uid, $partyId);
      // and the inviter joins the user's party 
      if ($this->_associateParty($partyId, $user_id))
      {
        $this->getCPOnJoin($partyId, $user_id);
      }
      $this->clearInvitesFor($partyId, $user_id);
      // in the next step the party owner (read: inviter)
      // gets Cheat Points if the number of members <= 11
    }
    else
      logBackendError('not invited', array($user_id, $partyId, 'SELECT '.getTableName('invited_people').'
      WHERE ip_inviter="'.$partyId.'" AND ip_invited="'.$user_id.'"
      '));
  }

}


?>
